<?php
/**
 * author:歪妻
 * Date: 2020/11/2 0002
 */

require_once 'lib/common.php';
require_once 'lib/view-post.php';
$postId = postId();
$pdo = getPDO();
$row = getView($pdo,$postId);

//如果帖子不存在，我们在这里处理
if (!$row)
{
    redirectAndExit('index.php?not-found=1');
}

$errors = null;
if ($_POST)
{
    $commentData = array(
        'name' => $_POST['comment-name'],
        'website' => $_POST['comment-website'],
        'text' => $_POST['comment-text'],
    );
    $errors = addCommentToPost($pdo, $postId, $commentData);
    // 如果没有错误，请重定向回自身并重新显示
    if (!$errors)
    {
        redirectAndExit('view-post.php?post_id=' . $postId);
    }
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>
        A blog application |
        <?php echo htmlEscape($row['title']) ?>
    </title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
<?php require 'templates/title.php' ?>

<h2>
    <?php echo htmlEscape($row['title']) ?>
</h2>

<div>
    <?php echo convertSqlDate($row['created_at']) ?>
</div>
<p>
    <?php // 这已经转义了，所以不需要进一步转义 ?>
    <?php echo convertNewlinesToParagraphs($row['body']) ?>

</p>
<h3><?php echo countCommentsForPost($postId) ?> 评论</h3>

<?php foreach (getCommentsForPost($postId) as $comment): ?>
    <hr />
    <div class="comment">
        <div class="comment-meta">
            评论 来自
            <?php echo htmlEscape($comment['name']) ?>
            at
            <?php echo convertSqlDate($comment['created_at']) ?></a>
        </div>
        <div class="comment-body">
            <a href="<?php echo htmlEscape($comment['website'])?>">个人中心</a>
        </div>
        <div class="comment-body">
            <?php echo htmlEscape($comment['text']) ?>
        </div>
    </div>
<?php endforeach ?>
<?php require 'templates/comments-form.php' ?>
</body>
</html>